/*global window: false*/
/*
 * #depends user-preferences-store.js
 * #depends new-version-window.js
 */
Ext.ns('Ext.ux.mattgoldspink.subsonic');

Ext.ux.mattgoldspink.subsonic.BottomBar = Ext.extend(Ext.Panel, {
    constructor: function(config) {
        Ext.apply(config, {
            cls: 'bottombar',
            plugins: ['msgbus'],
            bbar : new Ext.ux.StatusBar({
				id: 'bottombar',
                defaultText: 'subTunes ' + Ext.ux.mattgoldspink.subsonic.subTunesVersion,
                text: 'Ready',
                ref: 'status',
                iconCls: 'x-status-valid',
                statusAlign: 'right',
                items: [
					{
						iconCls: 'createPlaylist',
						cls: 'left createPlaylist',
						enableToggle: false,
						handler: this.addNewPlaylist,
						scope: this
					},
                    {
                        iconCls: 'shuffle',
						cls: 'left shuffle',
						enableToggle: true,
                        handler: this.handleShuffle,
						scope: this
                    },
                    { 
                        iconCls: 'repeat',
						cls: 'left repeat off',
						enableToggle: false,
                        handler: this.handleRepeat,
						scope: this
                    },
                    {
                        text: 'About',
                        handler: this.launchAbout
                    },
                    {
                        iconCls: 'cfg',
                        menu: this.makeSettingsMenu()
                    }
                ]
            })
        });
        Ext.ux.mattgoldspink.subsonic.BottomBar.superclass.constructor.apply(this, arguments);
        this.setupSubscriptions();
        this.checkForUpdates();
    },
    checkForUpdates: function(){
        window.callbackversion = function(data){
            var current = Ext.ux.mattgoldspink.subsonic.subTunesVersion;
            if (data.version === '{VER'+''+'SION}' || data.version === current) {
                return;
            }
            if (Ext.ux.mattgoldspink.subsonic.isVersionGreaterThan(current, data.version)){
                return;
            }
            Ext.getCmp('bottombar').defaultText = 'subTunes ' + data.version + ' is available! <a target="_blank" href="' + data.url + '">Click here to get it</a>';
        };
        $.ajax({
            dataType: 'jsonp',
            url: "http://subtunes.googlecode.com/files/version.js?callback=callbackversion",
            success: function(){ 
              // do nothing - above function handles it instead  
            }
        });
    },
    launchAbout: function(){
        new Ext.ux.mattgoldspink.subsonic.NewVersionWindow({}).show();
    },
    setupSubscriptions: function(){
        this.subscribe('subsonic.status', {
            fn: this.handleStatusUpdate,
            scope: this
        });
        this.subscribe('subsonic.status.clear', {
            fn: this.handleStatusClear,
            scope: this
        });
    },
	addNewPlaylist: function(){
		this.publish('subsonic.playlist.created', true);
	},
	handleRepeat: function(button, e){
		var toBeRemoved, toBeAdded, btnEl = button.getEl();
		if (btnEl.hasClass('off')) {
			toBeRemoved = 'off';
			toBeAdded = 'all';
		} else if (btnEl.hasClass('all')) {
			toBeRemoved = 'all';
			toBeAdded = 'one';
		} else {
			toBeRemoved = 'one';
			toBeAdded = 'off';
		}
		btnEl.removeClass(toBeRemoved);
		btnEl.addClass(toBeAdded);
		this.publish('subsonic.player.repeat', toBeAdded);
	},
	handleShuffle: function(){
		this.publish('subsonic.player.shuffle.toggle', true);
	},
    handleStatusClear: function(subject, msg) {
        this.getBottomToolbar().clearStatus({useDefaults:true});
    },
    handleStatusUpdate: function(subject, msg) {
        this.getBottomToolbar().showBusy();
        this.getBottomToolbar().setStatus({
            text: msg.text
        });
    },
    makeSettingsMenu: function(){
        var items = [], me = this;
        $.each(Ext.ux.mattgoldspink.subsonic.UserPrefsStore.defaults, function(key, val) {
            var item = Ext.apply({}, val);
            if (item.type === "boolean") {
                item.checked = Ext.ux.mattgoldspink.subsonic.UserPrefsStore.get(key);
				if (!Ext.isDefined(item.checkHandler)) {
					item.checkHandler = me.makeCheckHandler(key);
				}
            } else if (item.type === "string" || item.type === "number") {
				if (Ext.isDefined(item.makeHandler)) {
					item.handler = item.makeHandler(key, item);
				} else {
					item.handler = me.makeStringHandler(key, item);
				}
			}
            items.push(item);
        });
        return new Ext.menu.Menu({
            items: items
        });
    },
	makeStringHandler: function(key, item) {
		return function() {
			Ext.MessageBox.prompt(item.text, item.description, function(btn, text){
				Ext.ux.mattgoldspink.subsonic.UserPrefsStore.set(key, text);
			});
		};
	},
    makeCheckHandler: function(key){
        return function(item, checked) {
            Ext.ux.mattgoldspink.subsonic.UserPrefsStore.set(key, checked);
        };
    }
});
